package com.manor.main.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;

import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.activity.AbsActivity;
import com.manor.common.em.AuthType;
import com.manor.common.event.AuthResultEvent;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.http.HttpCallback;
import com.manor.common.http.PitUtil;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.AuthUtil;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.ProcessResultUtil;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StaIntentUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.common.utils.WordUtil;
import com.manor.main.R;
import com.manor.main.bean.MyEarningsBean;
import com.manor.main.dialog.AgentRechargePopup;
import com.manor.main.http.MainHttpUtil;

/**
 * 我的收益
 */
@Route(path = RouteUtil.PC_Earnings)
public class MyEarningsActivity extends AbsActivity implements View.OnClickListener {

    TextView tv_nengliang, tv_nengliangs, tv_shandui, tv_msg, tv_quanbu, tv_bl, tv_zhname;
    EditText ed_shuliang;
    RelativeLayout rl_confirm;
    LinearLayout ll_one, ll_two, ll_three, ll_tx, ll_Account;
    private TextView tvRight;

    private final Gson mGson = new Gson();
    private MyEarningsBean myEarningsBean;
    private String FaceRecognition = "";

    private String cashvote = "";
    private int my_bl = 0;
    private TextView tv_zh_id;
    private ProcessResultUtil mProcessResultUtil;
    private String agentTip = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_earnings;
    }

    @Override
    protected void main() {
        setTitle(WordUtil.getString(R.string.earnings));
        mProcessResultUtil = new ProcessResultUtil(this);
        tv_nengliang = findViewById(R.id.tv_nengliang);
        tv_nengliangs = findViewById(R.id.tv_nengliangs);
        tv_shandui = findViewById(R.id.tv_shandui);
        tv_quanbu = findViewById(R.id.tv_quanbu);
        rl_confirm = findViewById(R.id.rl_confirm);
        tv_msg = findViewById(R.id.tv_msg);
        ed_shuliang = findViewById(R.id.ed_shuliang);

        tvRight = findViewById(R.id.tv_right);
        tvRight.setOnClickListener(this);

        ll_one = findViewById(R.id.ll_one);
        ll_two = findViewById(R.id.ll_two);
        ll_three = findViewById(R.id.ll_three);
        ll_tx = findViewById(R.id.ll_tx);
        ll_Account = findViewById(R.id.ll_Account);
        tv_bl = findViewById(R.id.tv_bl);
        tv_zhname = findViewById(R.id.tv_zhname);
        tv_zh_id = findViewById(R.id.tv_zh_id);
        ed_shuliang.addTextChangedListener(textWatcher);
        ll_Account.setOnClickListener(this);
        ll_tx.setOnClickListener(this);
        rl_confirm.setOnClickListener(this);

        tv_quanbu.setOnClickListener(this);
        ll_one.setOnClickListener(this);
        ll_two.setOnClickListener(this);
        ll_three.setOnClickListener(this);
        EventBus.getDefault().register(this);

        doNet();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (mProcessResultUtil != null) {
            mProcessResultUtil.release();
        }
        mProcessResultUtil = null;
        super.onDestroy();
    }

    private void doNet() {
        MainHttpUtil.getMyEarnings(CommonAppConfig.getInstance().getUid(), CommonAppConfig.getInstance().getToken(),
                new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        if (code == 0 && info != null && StringUtil.isNotEmpty(info)) {
                            String result = PitUtil.strGetFirst(info);

                            myEarningsBean = mGson.fromJson(result, MyEarningsBean.class);
                            tv_nengliang.setText(myEarningsBean.getCredit2() + "");
                            tv_nengliangs.setText(myEarningsBean.getMoney() + "");
                            tv_shandui.setText(myEarningsBean.getCash() + "");

                            agentTip = myEarningsBean.getDaichong_tips();

                            try {
                                my_bl = Integer.parseInt(myEarningsBean.getCash_rate());
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                            CharSequence charSequence = Html.fromHtml(myEarningsBean.getTips(), new Html.ImageGetter() {

                                @Override
                                public Drawable getDrawable(String arg0) {
                                    Drawable drawable =
                                            MyEarningsActivity.this.getResources().getDrawable(R.mipmap.ic_launcher_round);
                                    //下面这句话不可缺少
                                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                                    return drawable;
                                }
                            }, null);
                            tv_msg.setText(charSequence + "");
                        } else {
                            ToastUtil.show(msg);
                        }
                    }
                });
    }

    private final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str = ed_shuliang.getText().toString();
            if (str.equals("")) {
                tv_bl.setText("");
                return;
            }

            tv_bl.setText(str);

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    private void setTx() {
        if (myEarningsBean == null) {
            return;
        }
        if (TextUtils.isEmpty(myEarningsBean.getCash()) && myEarningsBean.getCash().equals("0")) {
            ToastUtil.show("您还没有那么多余额");
            return;
        }
        if (StringUtil.isEmpty(myEarningsBean.getCash()) || StringUtil.isEmpty(ed_shuliang.getText().toString())) {
            ToastUtil.show("您还没有那么多余额");
            return;
        }
        if (new BigDecimal(myEarningsBean.getCash()).compareTo(new BigDecimal(ed_shuliang.getText().toString())) == -1) {
            ToastUtil.show("您还没有那么多余额");
            return;
        }

        if (my_id.equals("")) {
            ToastUtil.show("请选择收款账户");
            return;
        }
        cashvote = ed_shuliang.getText().toString();
        if (cashvote.equals("")) {
            ToastUtil.show("请选择收款数量");
            return;
        }

        String str = ed_shuliang.getText().toString();
        if (str.equals("")) {
            ToastUtil.show("请输入提取数量");
            return;
        }
        double a = 0;
        try {
            a = Double.parseDouble(str);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        double b = 0;
        try {
            b = Double.parseDouble(myEarningsBean.getCash());

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (a > b) {
            ToastUtil.show("提现嗨券不能大于当前余额");
            return;
        }


        CommonHttpUtil.ifAuth(new CommonCallback<Boolean>() {
            @Override
            public void callback(Boolean bean) {
                if (bean) {
                    doVerifyNext();
                } else {
                    setCamera(AuthType.TYPE_EXTRACT);
                }
            }
        });


    }


    private void doVerifyNext() {
        if (FaceRecognition.equals("")) {
            closeKeyBoard();
            new XPopup.Builder(mContext)
                    .asConfirm(null, "即将进入面部识别认证页面一旦认证成功，操作不可逆", "取消", "确定",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    setCamera(AuthType.TYPE_EXTRACT);
                                }
                            }, null, false, R.layout.dailog_my_earnings)
                    .show();

            return;
        }
        MainHttpUtil.getUserWithdrawal(CommonAppConfig.getInstance().getUid(), CommonAppConfig.getInstance().getToken(),
                my_id + "", cashvote, "2", FaceRecognition, new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        if (code == 0 && info != null && StringUtil.isNotEmpty(info)) {
                            ToastUtil.show(msg);
                            finish();
                        } else {
                            ToastUtil.show(msg);
                        }
                    }
                });
    }


    private void setCamera(AuthType type) {
        AuthUtil.instance.startCamera(this, new CommonCallback<Boolean>() {
            @Override
            public void callback(Boolean bean) {
                if (bean == true) {
                    RouteUtil.forwardFaceExp(type);
                } else {
                    ToastUtil.show("未完成认证");
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAuthResult(AuthResultEvent e) {
        if (e.getType() == AuthType.TYPE_EXTRACT)
            if (e.getCode() == 200) {
                FaceRecognition = e.getUrl();
                KLog.e("tag", FaceRecognition);
                setTx();
            } else {
                ToastUtil.show("检测失败");
            }
    }

    /**
     * 关闭键盘
     */
    public void closeKeyBoard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_confirm) {
            setTx();

        } else if (id == R.id.rl_pop) {

        } else if (id == R.id.tv_quanbu) {
            if (null != myEarningsBean) {

                ed_shuliang.setText(myEarningsBean.getCash() + "");


                String str = ed_shuliang.getText().toString();
                if (str.equals("")) {
                    tv_bl.setText("");
                    return;
                }
                tv_bl.setText(str);
            }
        } else if (id == R.id.ll_one) {
            if (null != myEarningsBean) {
                RouteUtil.forwardEarnings(RouteUtil.PC_Withdrawal, StaIntentUtil.NO_ENERGR);
            }
        } else if (id == R.id.ll_two) {
            if (null != myEarningsBean) {
                startActivity(new Intent(this, SdVolumeActivity.class));
            }
        } else if (id == R.id.ll_three) {
            if (null != myEarningsBean) {
                RouteUtil.forwardEarnings(RouteUtil.PC_Withdrawal, StaIntentUtil.FLASH_COUPONS);
            }
        } else if (id == R.id.ll_tx) {
            if (null != myEarningsBean) {
                RouteUtil.forwardEarnings(RouteUtil.PC_Withdrawal, StaIntentUtil.WITHDRAWAL_RECORD);
            }
        } else if (id == R.id.ll_Account) {//选择账户
            if (null != myEarningsBean) {
                RouteUtil.forwardAddAccountID(MyEarningsActivity.this, RouteUtil.PC_WithdrawalAccount, 10, my_id);
            }
        } else if (id == R.id.tv_right) {//代充 代理充值
            if (ClickUtil.canClick())

                CommonHttpUtil.ifAuth(new CommonCallback<Boolean>() {
                    @Override
                    public void callback(Boolean bean) {
                        if (bean) {
                            AgentRechargePopup.Companion.load(MyEarningsActivity.this, agentTip, new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    doNet();
                                }
                            });
                        } else {
                            ToastUtil.show("您尚未认证~");
                        }
                    }
                });

        }


    }

    String my_id = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && null != data) {
            my_id = data.getStringExtra("id");
            tv_zhname.setText(data.getStringExtra("context"));
            tv_zh_id.setText(data.getStringExtra("name"));

        }
        if (requestCode == Constants.CODE_REQUEST_FACE && resultCode == Constants.CODE_RESULT_FACE && data != null) {

            FaceRecognition = data.getStringExtra(Constants.URL);
            KLog.e("tag", FaceRecognition);
            setTx();
        }

    }
}
